<?php

class Front_Libraries_Auth_DMDAuthAdapter implements Zend_Auth_Adapter_Interface
{
    private $_username;
    private $_password;

    private $_user;
    /**
     * Sets username and password for authentication
     *
     * @return void
     */
    public function __construct($username, $password)
    {
        $this->_username = $username;
        $this->_password = $password;
    }

    /**
     * Performs an authentication attempt using Doctrine User class.
     *
     * @throws Zend_Auth_Adapter_Exception If authentication cannot
     *                                     be performed
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {
    	$result = null;

    	try {
            $em = Zend_Registry::get('entitymanager');

            $user = $em->getRepository('Entities\User')->findOneBy(array('username'=>$this->_username, 'active'=>1));

            if ($user == NULL) {
                $result = new Zend_Auth_Result(
                    Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
                    null,
                    array('sorry, login ' . $this->_username . ' was not found'));
            } else {
                if ($user->getPassword() != md5($this->_password)) {
                    $result = new Zend_Auth_Result(
                        Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
                        $user,
                        array('sorry, the password you entered was invalid for user ' .
                                $this->_username));
                } else {
                    $user->setRolesArray($em->getRepository('Entities\User')->getRolesArray($user->getId()));
                    $result = new Zend_Auth_Result(
                        Zend_Auth_Result::SUCCESS,
                        $user,
                        array());
                    $this->_user = $user;
                }
            }
            return $result;
    	} catch(Exception $e) {
            throw new Zend_Auth_Adapter_Exception($e->getMessage());
    	}
    }
    
    public function getResultObject()
    {
        return $this->_user;
    }
}
